<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.realname"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="搜索真实姓名"
      />
      <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="搜索Id"
      />
      <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="搜索用户Id"
      />
      <el-input
        v-model="listQuery.phone"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="搜索手机号"
      />
      <el-select
        v-model="listQuery.status"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择状态"
      >
        <el-option v-for="(item, index) in statusMap" :key="index" :label="item.label" :value="item.value" />
      </el-select>
      <el-button
        v-permission="['operation:distribution:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getList"
      >查找</el-button>
      <el-button
        v-permission="['operation:distribution:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="createDialogBtn"
      >添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="身份证">
              <span>{{ props.row.idCard }}</span>
            </el-form-item>
          </el-form>
          <el-form label-position="right" class="table-expand">
            <el-form-item label="上级Id">
              <span>{{ props.row.parentId }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column align="center" label="ID" width="80" prop="id" />

      <el-table-column align="center" label="用户Id" width="80" prop="userId" />

      <el-table-column align="center" label="状态" width="100" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'error' ">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="等级" width="110" prop="level" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.level == 2 ? 'success' : 'error' ">{{ scope.row.level }}级分销</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="真实姓名" prop="realname" />

      <el-table-column align="center" label="手机号" prop="phone" />

      <el-table-column align="center" label="下线" width="120" prop="balance" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.allowChild === 1 ? 'success' : 'error'">{{ scope.row.allowChild === 1 ? '允许发展' : '不许发展' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="余额" width="120" prop="balance" >
        <template slot-scope="scope">
          <el-tag type="success">￥{{ scope.row.balance / 100.0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="冻结余额" width="120" prop="balance" >
        <template slot-scope="scope">
          <el-tag type="error">￥{{ scope.row.freezeBalance / 100.0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="总分销额" width="120" prop="balance" >
        <template slot-scope="scope">
          <el-tag type="error">￥{{ scope.row.totalSum / 100.0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" width="180" label="创建时间" prop="gmtCreate">
        <template slot-scope="scope">{{ scope.row.gmtCreate | formatTime }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['operation:distribution:detail']"
            class="filter-item"
            type="warning"
            icon="el-icon-s-order"
            size="mini"
            @click="showDetailList(scope.row)"
          >详情</el-button>
          <el-button
            v-permission="['operation:distribution:edit']"
            type="primary"
            size="mini"
            @click="updateDialogBtn(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['operation:distribution:delete']"
            type="danger"
            size="mini"
            @click="deleteDistributionBtn(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        v-loading="diglogLoadding"
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>

        <el-form-item label="用户" prop="userId">
          <el-select
            v-model="dataForm.userId"
            :disabled="dialogStatus === 'update'"
            :remote-method="searchUserNickname"
            placeholder="请搜索用户昵称"
            filterable
            remote
            reserve-keyword
            @change="searchNicknameUserChange">
            <el-option
              v-for="item in keyRes"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select
            v-model="dataForm.level"
            :disabled="dialogStatus === 'update'"
            class="filter-item"
            placeholder="选择等级"
          >
            <el-option v-for="(item, index) in levelMap" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dataForm.level && dataForm.level > 1" label="上级" prop="parentId">
          <el-select
            v-model="dataForm.parentId"
            :remote-method="searchUserNickname"
            :disabled="dialogStatus === 'update'"
            placeholder="请搜索用户昵称"
            filterable
            remote
            reserve-keyword
            @change="searchNicknameParentChange">
            <el-option
              v-for="item in keyRes"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="dataForm.status"
            style="width: 200px"
            class="filter-item"
            placeholder="请选择状态"
          >
            <el-option v-for="(item, index) in statusMap" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发展下线" prop="allowChild">
          <el-select
            v-model="dataForm.allowChild"
            style="width: 200px"
            class="filter-item"
            placeholder="请选择状态"
          >
            <el-option :value="1" label="允许发展下线" />
            <el-option :value="0" label="不允许发展下线" />
          </el-select>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input
            v-model="dataForm.realname"
            clearable
            class="filter-item"
            placeholder="输入用户真实姓名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="dataForm.phone"
            clearable
            class="filter-item"
            placeholder="输入用户手机号"
          />
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input
            v-model="dataForm.idCard"
            clearable
            class="filter-item"
            placeholder="输入用户身份证号"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" :loading="submitting" type="primary" @click="handleCreate">确定</el-button>
        <el-button v-else :loading="submitting" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :visible.sync="dialogDetailListVisible" title="详情">
      <el-table
        v-loading="listDetailLoading"
        :data="listDetail"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="ID" prop="id" />

        <el-table-column align="center" label="订单号" prop="orderNo" />

        <el-table-column align="center" label="描述" prop="description" />

        <el-table-column align="center" label="余额变化" prop="balanceDelta">
          <template slot-scope="scope">
            {{ scope.row.balanceDelta / 100.0 }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="冻结变化" prop="freezeBalanceDelta">
          <template slot-scope="scope">
            {{ scope.row.freezeBalanceDelta / 100.0 }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="余额结算" prop="balance">
          <template slot-scope="scope">
            {{ scope.row.balance / 100.0 }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="冻结结算" prop="balance">
          <template slot-scope="scope">
            {{ scope.row.freezeBalance / 100.0 }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="detailTotal>0"
        :total="detailTotal"
        :page.sync="listDetailQuery.page"
        :limit.sync="listDetailQuery.limit"
        :page-size="5"
        :page-sizes="[5, 10, 20, 30]"
        @pagination="showDetailList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailListVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listDistribution, createDistribution, deleteDistribution, updateDistribution, listDistributionDetail } from '@/api/distribution'
import { searchUser, searchUserId } from '@/api/user'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import ElOption from '../../../node_modules/element-ui/packages/select/src/option' // Secondary package based on el-pagination

const statusMap = [{
  value: 0,
  label: '冻结'
}, {
  value: 1,
  label: '激活'
}]

const levelMap = [
  {
    value: 1,
    label: '一级分销'
  },
  {
    value: 2,
    label: '二级分销'
  },
  {
    value: 3,
    label: '三级分销'
  }
]

export default {
  name: 'Distribution',
  components: {
    ElOption,
    Pagination
  },
  filters: {
    statusFilter(code) {
      return statusMap[code].label
    }
  },
  data() {
    return {
      uploadPath,
      list: [],
      listDetail: [],
      keyRes: [],
      searchUserRes: [],
      total: 0,
      detailTotal: 0,
      diglogLoadding: false,
      listLoading: true,
      listDetailLoading: true,
      targetDistributionId: undefined,
      statusMap,
      levelMap,
      listQuery: {
        page: 1,
        limit: 20,
        userId: undefined,
        realname: undefined,
        idCard: undefined,
        phone: undefined
      },
      listDetailQuery: {
        page: 1,
        limit: 5
      },
      dataForm: {
        id: undefined,
        userId: undefined,
        parentId: undefined,
        status: undefined,
        realname: undefined,
        idCard: undefined,
        phone: undefined,
        level: undefined,
        allowChild: undefined
      },
      dialogFormVisible: false,
      dialogDetailListVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '等级不能为空', trigger: 'blur' }],
        realname: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
        allowChild: [{ required: true, message: '请选择是否允许该用户发展下线', trigger: 'blur' }]
      },
      submitting: false
    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listDistribution(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    query() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        userId: undefined,
        parentId: undefined,
        status: undefined,
        realname: undefined,
        idCard: undefined,
        phone: undefined,
        level: undefined,
        nickname: undefined,
        parentNickname: undefined,
        allowChild: undefined
      }
      this.diglogLoadding = false
      this.dialogStatus = 'create'
    },
    updateDialogBtn(row) {
      this.dialogStatus = 'update'
      this.diglogLoadding = true
      this.dialogFormVisible = true
      this.dataForm = Object.assign({
        id: row.id,
        level: row.level,
        parentId: row.parentId,
        status: row.status,
        realname: row.realname,
        idCard: row.idCard,
        allowChild: row.allowChild,
        phone: row.phone
      }, {})
      // 1. 查询名称映射
      this.keyRes = []
      searchUserId(row.userId)
        .then(res => {
          this.keyRes.push({
            value: res.data.data.id,
            label: res.data.data.nickname
          })
          this.diglogLoadding = false
        })
      // 2. 封装到dataForm对象中
      if (row.parentId > 0) {
        searchUserId(row.userId)
          .then(res => {
            this.keyRes.push({
              value: res.data.data.id,
              label: res.data.data.nickname
            })
            this.diglogLoadding = false
          })
      }
    },
    createDialogBtn() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submitting = true
          createDistribution(this.dataForm)
            .then(response => {
            // 需要后台返回值
            // this.list.unshift(response.data.data)
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.submitting = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submitting = false
            })
        }
      })
    },
    handleUpdate() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submitting = true
          updateDistribution(this.dataForm)
            .then(response => {
            // 需要后台返回值
            // this.list.unshift(response.data.data)
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新信息成功'
              })
              this.submitting = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submitting = false
            })
        }
      })
    },
    deleteDistributionBtn(row) {
      this.$confirm('此操作将永久删除该分销用户--' + row.id + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDistribution(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    searchUserNickname(e) {
      if (!e) {
        return
      }
      searchUser(e)
        .then(res => {
          this.searchUserRes = res.data.data
          const array = []
          if (this.searchUserRes.length > 0) {
            this.searchUserRes.forEach(item => {
              array.push({
                value: item.id,
                label: item.nickname
              })
            })
          }
          this.keyRes = array
        })
    },
    searchNicknameUserChange(e) {
      for (let i = 0; i < this.searchUserRes.length; i++) {
        if (this.searchUserRes[i].id === e) {
          this.dataForm.userId = e
        }
      }
    },
    searchNicknameParentChange(e) {
      for (let i = 0; i < this.searchUserRes.length; i++) {
        if (this.searchUserRes[i].id === e) {
          this.dataForm.parentId = e
        }
      }
    },
    showDetailList(row) {
      // 1.全局loadding
      this.listDetailLoading = true
      if (row && row.id) {
        this.targetDistributionId = row.id
      }
      this.listDetailQuery.distributionId = this.targetDistributionId
      this.dialogDetailListVisible = true
      listDistributionDetail(this.listDetailQuery).then(res => {
        this.listDetail = res.data.data.items
        this.detailTotal = res.data.data.total
        this.listDetailLoading = false
      })
        .catch(response => {
          this.listDetailLoading = false
          this.dialogDetailListVisible = false
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    }
  }
}
</script>
